package com.zhaowb.springcloud.common.context;

import com.zhaowb.springcloud.common.constant.CommonConstants;
import com.zhaowb.springcloud.common.util.StringHelper;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IDEA
 *
 * @author zhaowb
 * @date 2018/10/23 21:28
 */
public class BaseContextHandler {
    private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(16);
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(16);
            threadLocal.set(map);
        }
        return map.get(key);
    }

    /**
     * 获取用户ID
     *
     * @return
     */
    public static String getUserID() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_ID);
        return StringHelper.getObjectValue(value);
    }

    /**
     * 获取用户名
     *
     * @return
     */
    public static String getUserName() {
        Object value = get(CommonConstants.CONTEXT_KEY_USERNAME);
        return StringHelper.getObjectValue(value);
    }

    /**
     * 获取用户姓名
     *
     * @return
     */
    public static String getName() {
        Object value = get(CommonConstants.CONTEXT_KEY_USER_NAME);
        return StringHelper.getObjectValue(value);
    }

    public static void setUserID(String userID) {
        set(CommonConstants.CONTEXT_KEY_USER_ID, userID);
    }

    public static void setUserName(String userName) {
        set(CommonConstants.CONTEXT_KEY_USERNAME, userName);
    }

    public static void setName(String name) {
        set(CommonConstants.CONTEXT_KEY_USER_NAME, name);
    }

    public static void remove() {
        threadLocal.remove();
    }
}
